package com.astrocsr.security;

import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import com.astrocsr.business.UserManager;
import com.astrocsr.common.Constants;
import com.astrocsr.common.helper.ConfigHelper;
import com.astrocsr.common.helper.EncryptionHelper;
import com.astrocsr.domain.web.UserInfo;

public class AuthenticationCustomProvider implements AuthenticationProvider {
 
	static final Logger log = Logger.getLogger(AuthenticationCustomProvider.class);

	@Autowired
	private UserManager userManager;
	
	@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	
    	try {
	        String username = authentication.getName();
	        String password = (String) authentication.getCredentials();
	
	        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
		        UserInfo details = userManager.getUserByEmail(username);
	
		        if (details != null) {
		        	
					// check locked or not.
					if (Constants.YES.equalsIgnoreCase(details.getLocked())) {
						throw new BadCredentialsException(username + Constants.SPLIT + ConfigHelper.getInstance().get("system.authentication.locked"));
					}
	
		        	if (details.getPassword() != null &&
		        		details.getPassword().equals(EncryptionHelper.encodeMD5(password))) {
		        		
					    WebUserDetails principal = new AppWebUserDetails(details, details.getGroupCode());
					    
					    // update Last Login
					    userManager.updateLastLogin(username);
					    
					    return new UsernamePasswordAuthenticationToken(principal, password, principal.getAuthorities());
		        	}
		        }
	        }
	        throw new BadCredentialsException(username + Constants.SPLIT + ConfigHelper.getInstance().get("system.authentication.error"));

    	} catch(BadCredentialsException be) {
    		throw be;
    	} catch(SQLException e) {
    		log.error(e.getMessage(), e);
			throw new BadCredentialsException(ConfigHelper.getInstance().get("system.authentication.error"));
    	} catch(Exception e) {
    		log.error(e.getMessage(), e);
    		throw new BadCredentialsException(ConfigHelper.getInstance().get("system.authentication.error"));
			
    	} finally {

    	}
    }
 
    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}